package com.cwh.taskcenter.lock.impl;

import com.cwh.taskcenter.lock.DistributedLock;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @author cwh
 */
@ConditionalOnProperty(
        prefix = "distributed.lock",
        name = "type",
        havingValue = "REDIS"
)
@Component
@RequiredArgsConstructor
public class RedisDistributedLock implements DistributedLock {

    private final RedissonClient redissonClient;

    @Override
    public boolean tryLock(String lockKey,long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    @Override
    public <T> T executeInLock(Supplier<T> supplier, long waitTime, long leaseTime, TimeUnit unit) {
        return null;
    }

    @Override
    public void executeInLock(Runnable runnable, long waitTime, long leaseTime, TimeUnit unit) {

    }
}
